﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;

using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Market;

namespace EShop.Services.Market
{
    public class AdvertiseService:IAdvertise
    {
        #region Constants
        private const string ADVERTISE_BY_ID_KEY = "EShop.Advertise.id-{0}";
        private const string ADVERTISE_PATTERN_KEY = "EShop.Advertise";
        #endregion

        #region Fields
        private readonly IRepository<Advertise> _advertiseRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public AdvertiseService(IRepository<Advertise> advertiseRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _advertiseRepository = advertiseRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
        #endregion

        #region Methods

        /// <summary>
        /// 添加广告
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddBrand(Advertise model)
        {
            if (model == null) throw new ExtException("NUll Advertise Model");

            int rs = _advertiseRepository.Insert(model);
            if (rs > 0)
            {
                rs = 1;
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs;
        }

        /// <summary>
        /// 修改广告
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateAdvertise(Advertise model)
        {

            if (model == null) throw new ExtException("NUll Advertise Model");

            int rs = _advertiseRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityUpdated(model);

            }
            return rs > 0 ? true : false;
        }

        /// <summary>
        /// 获取全部的广告
        /// </summary>
        /// <param name="showHidden">是否需要显示未发布的广告</param>
        /// <returns></returns>
        public List<Advertise> GetAllAdvertise(bool showHidden = false)
        {
            var query = _advertiseRepository.Table;
            if (!showHidden)
                query = query.Where(c => !c.Deleted);

            query = query.OrderBy(c => c.CreateTime);
            var unsortedAdvertise = query.ToList();

            //sort categories

            return unsortedAdvertise;
        }
        /// <summary>
        /// 获取全部广告
        /// </summary>
        /// <returns></returns>
        public IPagedList<Advertise> GetAllAdvertise(int pageIndex, int pageSize, bool showHidden = false)
        {
            var advertise = GetAllAdvertise(showHidden);
            //filter
            return new PagedList<Advertise>(advertise, pageIndex, pageSize);
        }
        /// <summary>
        /// 获取一条广告
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Advertise> GetAdvertiseByFiter(DateTime? starttime, DateTime? endtime, string Adurl, string Adname, string Flag,bool showHidde=false)
        {
            var query = _advertiseRepository.Table;
            //是否有开始时间
            if(starttime.HasValue)  query=query.Where(c=>c.AdStartTime>=starttime.Value);
            //是否有结束时间
            if (endtime.HasValue) query = query.Where(c => c.AdEndTime <= endtime.Value);
            //广告跳转地址
            if (!string.IsNullOrEmpty(Adurl)) query = query.Where(c => c.Adurl == Adurl);
            //广告名字，唯一值
            if (!string.IsNullOrEmpty(Adname)) query = query.Where(c => c.Adname == Adname);
            int result=0;
            if (!string.IsNullOrEmpty(Flag) && int.TryParse(Flag, out result)) query = query.Where(c => c.Flag == result);

            var advertise = query.OrderBy(c => c.CreateTime);
            return advertise.ToList();
        }
        /// <summary>
        /// 获得一条广告信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Advertise GetAdvertiseById(int id)
        {
            if (id <= 0)
                return null;
            //格式化缓存条件
            string key = string.Format(ADVERTISE_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var advertise = _advertiseRepository.GetById(id);
                return advertise;
            });
        }
        ///// <summary>
        ///// 根据指定条件获取广告信息
        ///// </summary>
        ///// <param name="fiter"></param>
        ///// <returns></returns>
        //public DataTable GetAdByFiter(string fiter)
        //{

        //    string str_sql = "select * from [tb_mc_ad] where " + fiter;
        //    Library.SqlProvider.OleDb db = new Library.SqlProvider.OleDb();
        //    DataTable dt = new DataTable();
        //    try
        //    {
        //        dt = db.ExecuteDataset(COMM.PucConfig.ConnectionStringA, CommandType.Text, str_sql).Tables[0];
        //    }
        //    catch (Exception ex) { }
        //    return dt;
        //}
        /// <summary>
        /// 取得首页广告中间部分
        /// </summary>
        /// <returns></returns>
        public List<Advertise> GetPicAdvertise(int pagesize)
        {
            var advertise= GetAdvertiseByFiter(null, null, null, null, "1", false);
            return advertise.Where(c => c.AdStartTime > DateTime.Now && c.AdEndTime < DateTime.Now).
                OrderBy(c=>c.CreateTime).Take(pagesize).ToList();
        }

        /// <summary>
        /// 获得首页广告文字部分
        /// </summary>
        /// <returns></returns>
        public List<Advertise> GetTxtAdvertise(int pagesize)
        {

            var advertise = GetAdvertiseByFiter(null, null, null, null, "2", false);
            return advertise.Where(c => c.AdStartTime > DateTime.Now && c.AdEndTime < DateTime.Now).
                OrderBy(c => c.CreateTime).Take(pagesize).ToList();
        }
        /// <summary>
        /// 返回首页所需要的modellist
        /// </summary>
        /// <returns></returns>
        public List<Advertise> GetAdvertise(int pagesize)
        {

            var advertise = GetAdvertiseByFiter(null, null, null, null,null, false);
            return advertise.Where(c => c.AdStartTime > DateTime.Now && c.AdEndTime < DateTime.Now).
                OrderBy(c => c.CreateTime).Take(pagesize).ToList();
        }

        /// <summary>
        /// 按id从列表里取得指定广告
        /// </summary>
        /// <param name="models"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<Advertise> GetAdvertiseFromId(string id)
        {
            
            //string[] ids = id.Split(',');
            //_advertiseRepository.Table.Where(c =>ids.Contains<string>("").Equals(c.Id)); 
            return null;
        }
        #endregion
    }
}
